/**
 * 订单管理服务
 * 基于后端订单管理接口实现
 * 
 * 接口文档参考: FRONTEND_QUICK_START.md
 */

import http from './api.js'

// 订单状态映射
const ORDER_STATUS = {
    pending: '待支付',
    paid: '已支付',
    preparing: '备货中',
    shipping: '配送中',
    delivered: '已送达',
    cancelled: '已取消',
    refunded: '已退款'
}

// 订单服务
const orderService = {
    /**
     * 创建订单
     * POST /api/v1/orders
     * 
     * @param {Object} orderData 订单数据
     * @param {Number} orderData.merchantId - 商家ID
     * @param {Number} orderData.addressId - 地址ID（可选，拼单订单可以为空）
     * @param {String} orderData.scheduledDeliveryDate - 预约配送日期 (YYYY-MM-DD)
     * @param {String} orderData.scheduledDeliveryTime - 预约配送时间段 (如: "12:00-14:00")
     * @param {Array} orderData.items - 订单商品列表
     * @param {Number} orderData.items[].foodId - 商品ID
     * @param {Number} orderData.items[].quantity - 购买数量
     * @param {String} orderData.items[].spiceLevel - 辣度选择
     * @param {String} orderData.notes - 备注（可选）
     * @param {Number} orderData.activityId - 拼单活动ID（可选，用于关联拼单）
     */
    createOrder: async (orderData) => {
        try {
            console.log('创建订单 - 请求数据:', orderData)

            const requestData = {
                merchantId: orderData.merchantId,
                scheduledDeliveryDate: orderData.scheduledDeliveryDate,
                scheduledDeliveryTime: orderData.scheduledDeliveryTime,
                items: orderData.items,
                notes: orderData.notes || ''
            }

            // 如果有地址ID，添加到请求中
            if (orderData.addressId) {
                requestData.addressId = orderData.addressId
            }

            // 如果有拼单活动ID，添加到请求中
            if (orderData.activityId) {
                requestData.activityId = orderData.activityId
                console.log('🔑 关联拼单活动:', orderData.activityId)
            }

            const response = await http.post('/orders', requestData, {
                needAuth: true,
                showLoading: true,
                loadingText: '创建订单中...'
            })

            console.log('创建订单 - 响应:', response)
            return response
        } catch (error) {
            console.error('创建订单失败:', error)
            throw error
        }
    },

    /**
     * 获取订单列表
     * GET /api/v1/orders
     * 
     * @param {Object} params 查询参数
     * @param {Number} params.page - 页码（默认1）
     * @param {Number} params.perPage - 每页数量（默认10）
     * @param {String} params.status - 订单状态筛选（可选）
     */
    getOrderList: async (params = {}) => {
        try {
            const queryParams = {
                page: params.page || 1,
                per_page: params.perPage || 10
            }

            // 如果指定了状态，添加到查询参数
            if (params.status) {
                queryParams.status = params.status
            }

            console.log('获取订单列表 - 查询参数:', queryParams)

            const response = await http.get('/orders', queryParams, {
                needAuth: true
            })

            console.log('获取订单列表 - 响应:', response)
            return response
        } catch (error) {
            console.error('获取订单列表失败:', error)
            throw error
        }
    },

    /**
     * 获取订单详情
     * GET /api/v1/orders/{id}
     * 
     * @param {Number} orderId 订单ID
     */
    getOrderDetail: async (orderId) => {
        try {
            console.log('获取订单详情 - 订单ID:', orderId)

            const response = await http.get(`/orders/${orderId}`, {}, {
                needAuth: true
            })

            console.log('获取订单详情 - 响应:', response)
            return response
        } catch (error) {
            console.error('获取订单详情失败:', error)
            throw error
        }
    },

    /**
     * 取消订单
     * PUT /api/v1/orders/{id}/cancel
     * 
     * @param {Number} orderId 订单ID
     * @param {String} reason 取消原因（可选）
     */
    cancelOrder: async (orderId, reason = '') => {
        try {
            console.log('取消订单 - 订单ID:', orderId, '原因:', reason)

            const response = await http.put(`/orders/${orderId}/cancel`, {
                reason: reason
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '取消订单中...'
            })

            console.log('取消订单 - 响应:', response)
            return response
        } catch (error) {
            console.error('取消订单失败:', error)
            throw error
        }
    },

    /**
     * 支付订单
     * PUT /api/v1/orders/{id}/pay
     * 
     * @param {Number} orderId 订单ID
     * @param {String} paymentMethod 支付方式（可选，如: 'wechat', 'alipay'）
     */
    payOrder: async (orderId, paymentMethod = 'wechat') => {
        try {
            console.log('支付订单 - 订单ID:', orderId, '支付方式:', paymentMethod)

            const response = await http.put(`/orders/${orderId}/pay`, {
                paymentMethod: paymentMethod
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '支付中...'
            })

            console.log('支付订单 - 响应:', response)
            return response
        } catch (error) {
            console.error('支付订单失败:', error)
            throw error
        }
    },

    /**
     * 申请退款
     * PUT /api/v1/orders/{id}/refund
     * 
     * @param {Number} orderId 订单ID
     * @param {String} reason 退款原因
     */
    refundOrder: async (orderId, reason = '') => {
        try {
            console.log('申请退款 - 订单ID:', orderId, '原因:', reason)

            const response = await http.put(`/orders/${orderId}/refund`, {
                reason: reason
            }, {
                needAuth: true,
                showLoading: true,
                loadingText: '申请退款中...'
            })

            console.log('申请退款 - 响应:', response)
            return response
        } catch (error) {
            console.error('申请退款失败:', error)
            throw error
        }
    },

    /**
     * 确认收货
     * POST /api/v1/orders/{id}/confirm
     * 
     * @param {Number} orderId - 订单ID
     * @returns {Promise} 确认收货结果
     */
    confirmReceipt: async (orderId) => {
        try {
            console.log('确认收货 - 订单ID:', orderId)
            
            const response = await http.post(`/orders/${orderId}/confirm`, {}, {
                needAuth: true,
                showLoading: true,
                loadingText: '处理中...'
            })
            
            console.log('✅ 确认收货成功:', response)
            return response
            
        } catch (error) {
            console.error('❌ 确认收货失败:', error)
            throw error
        }
    },

    /**
     * 获取订单状态文本
     * @param {String} status 订单状态
     */
    getStatusText: (status) => {
        return ORDER_STATUS[status] || '未知状态'
    },

    /**
     * 格式化订单数据（用于列表展示）
     * @param {Object} order 订单对象
     */
    formatOrderForList: (order) => {
        // 计算第一个商品的信息（用于卡片展示）
        const firstItem = order.items && order.items.length > 0 ? order.items[0] : null

        return {
            id: order.id,
            orderNo: order.order_no || order.orderNo,
            storeName: order.merchant_name || order.merchantName || '商家',
            status: order.status,
            statusText: orderService.getStatusText(order.status),

            // 商品信息（展示第一个商品）
            image: firstItem ? firstItem.food_image || firstItem.foodImage : '/static/food1.jpg',
            name: firstItem ? firstItem.food_name || firstItem.foodName : '商品',
            spice: firstItem ? firstItem.spice_level || firstItem.spiceLevel || '不辣' : '不辣',
            quantity: firstItem ? firstItem.quantity : 1,

            // 价格信息
            totalPrice: order.total_amount || order.totalAmount || 0,
            foodAmount: order.food_amount || order.foodAmount || 0,
            deliveryFee: order.delivery_fee || order.deliveryFee || 0,

            // 配送信息
            deliveryDate: order.scheduled_delivery_date || order.scheduledDeliveryDate,
            deliveryTime: order.scheduled_delivery_time || order.scheduledDeliveryTime,

            // 时间信息
            createdAt: order.created_at || order.createdAt,
            paidAt: order.paid_at || order.paidAt,

            // 拼单信息
            activityId: order.activity_id || order.activityId || null,
            isGroupBuying: !!(order.activity_id || order.activityId),

            // 其他信息
            itemCount: order.items ? order.items.length : 0,
            notes: order.notes || ''
        }
    },

    /**
     * 格式化订单数据（用于详情展示）
     * @param {Object} order 订单对象
     */
    formatOrderDetail: (order) => {
        return {
            id: order.id,
            orderNo: order.order_no || order.orderNo,
            status: order.status,
            statusText: orderService.getStatusText(order.status),

            // 商家信息
            merchantId: order.merchant_id || order.merchantId,
            merchantName: order.merchant_name || order.merchantName,

            // 收货信息
            deliveryName: order.delivery_name || order.deliveryName,
            deliveryPhone: order.delivery_phone || order.deliveryPhone,
            deliveryAddress: order.delivery_address || order.deliveryAddress,

            // 配送信息
            scheduledDeliveryDate: order.scheduled_delivery_date || order.scheduledDeliveryDate,
            scheduledDeliveryTime: order.scheduled_delivery_time || order.scheduledDeliveryTime,
            actualDeliveryTime: order.actual_delivery_time || order.actualDeliveryTime,

            // 价格信息
            foodAmount: order.food_amount || order.foodAmount || 0,
            deliveryFee: order.delivery_fee || order.deliveryFee || 0,
            totalAmount: order.total_amount || order.totalAmount || 0,

            // 订单商品
            items: (order.items || []).map(item => ({
                id: item.id,
                foodId: item.food_id || item.foodId,
                foodName: item.food_name || item.foodName,
                foodImage: item.food_image || item.foodImage,
                foodPrice: item.food_price || item.foodPrice,
                quantity: item.quantity,
                spiceLevel: item.spice_level || item.spiceLevel,
                subtotal: item.subtotal
            })),

            // 备注和原因
            notes: order.notes || '',
            cancelReason: order.cancel_reason || order.cancelReason || '',
            refundReason: order.refund_reason || order.refundReason || '',

            // 时间信息
            createdAt: order.created_at || order.createdAt,
            paidAt: order.paid_at || order.paidAt,
            cancelledAt: order.cancelled_at || order.cancelledAt,
            refundedAt: order.refunded_at || order.refundedAt,
            updatedAt: order.updated_at || order.updatedAt
        }
    }
}

export default orderService

